using System.Collections;
using System.Threading;
using BuildStatusIndicator.Controller.Events;

namespace BuildStatusIndicator.Controller.EventBroker
{
    public class BuildStatusEventPublisher : IBuildStatusEventPublisher
    {
        private readonly SynchronizationContext _context;
        private readonly IList _listeners = new ArrayList();

        public BuildStatusEventPublisher(SynchronizationContext context)
        {
            _context = context;
        }

        #region IBuildStatusEventPublisher Members

        public void PublishEvent<T>(T subject)
        {
            // _listeners is just an ArrayList of all the Listeners
            foreach (object listener in _listeners)
            {
                // Determine if a Listener handles the message of type T
                // by trying to cast it
                var receiver = listener as IListener<T>;
                if (receiver != null)
                {
                    // I'm using SyncronizationContext to handle moving processing
                    // from a background thread to the UI thread without having
                    // to worry about it in the View or Presenter
                    _context.Send(delegate { receiver.Handle(subject); }, null);
                }
            }
        }

        public void AddListener(object listener)
        {
            _listeners.Add(listener);
        }

        public void RemoveListener(object listener)
        {
            _listeners.Remove(listener);
        }

        #endregion
    }
}